/*
 *   This File is Part of CuteOgre Game Engine
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *	Copyright 2010 Alexandre Pires ( c.alexandre.pires@gmail.com )
 *  Created on: 2010/08/22
 */

#ifndef STATEMANAGER_H_
#define STATEMANAGER_H_

#include "IManager.h"
#include "Singleton.h"
#include "AbstractGameState.h"
#include "ScriptManager.h"

#include <QThread>
#include <QVector>
#include <QMap>
#include <QSharedPointer>
#include <QScriptEngine>

class StateManager :
		public QThread,
		public IManager,
		public Singleton<StateManager> {

	friend class InputManager;
	friend class GameEngine;

Q_OBJECT

	typedef QVector<AbstractGameState*> GameStates;
	typedef QMap<QString, AbstractGameState*> GameStatesMap;

private:
	GameStates mStates;
	GameStatesMap mAvailableStates;
	bool mShutdown;
	QScriptEngine mEngine;

protected:

	StateManager () :
		QThread (), mShutdown ( true ) {
	}

	void run ();

	void injectKeyPressed ( int rKey, unsigned int rText );
	void injectKeyReleased ( int rKey );
	void injectMouseMoved ( int rX, int rY, int rZ );
	void injectMousePressed ( int rX, int rY, int rMouseButton );
	void injectMouseReleased ( int rX, int rY, int rMouseButton );

public:
	~StateManager () {
	}

	static StateManager* getSingletonPtr ( void ) {
		return ms_Singleton;
	}

	static StateManager& getSingleton ( void ) {
		assert( ms_Singleton );
		return ( *ms_Singleton );
	}

	void init ();
	void shutdown ();

	void changeState ( const QString& rStateName, const QString& rScript = QString::null );
	void pushState ( const QString& rStateName, const QString& rScript = QString::null );
	void popState ();

	inline void sendScriptEvent ( const QString& rCode ) {
		ScriptManager::evaluate( rCode, &mEngine );
	}

	inline static void scriptEvent ( const QString& rCode ) {
		StateManager::getSingleton().sendScriptEvent ( rCode );
	}

	inline static void change ( const QString& rStateName, const QString& rScript = QString::null ) {
		StateManager::getSingleton().changeState( rStateName, rScript );
	}

	inline static void push ( const QString& rStateName, const QString& rScript = QString::null ) {
		StateManager::getSingleton().pushState( rStateName, rScript );
	}

	inline static void pop () {
		StateManager::getSingleton().popState();
	}

private:
	void updateState ();

};

#endif /* STATEMANAGER_H_ */
